import axios from './axios-config';
import { addUser } from '../api/user';

// 测试用户数据模板
const testUserTemplates = [
  {
    name: '张三',
    nickname: '小张',
    username: 'zhangsan',
    password: '123456',
    gender: 1, // 1代表男性
    height: 175,
    weight: 70,
    age: 28,
    goal: '减脂',
    dailyCalorieGoal: 2000,
    isActive: true,
    role: 'user',
    email: 'zhangsan@example.com'
  },
  {
    name: '李四',
    nickname: '小李',
    username: 'lisi',
    password: '123456',
    gender: 1,
    height: 180,
    weight: 75,
    age: 30,
    goal: '增肌',
    dailyCalorieGoal: 2500,
    isActive: true,
    role: 'user',
    email: 'lisi@example.com'
  },
  {
    name: '王五',
    nickname: '小王',
    username: 'wangwu',
    password: '123456',
    gender: 1,
    height: 172,
    weight: 65,
    age: 26,
    goal: '健康饮食',
    dailyCalorieGoal: 1800,
    isActive: false,
    role: 'user',
    email: 'wangwu@example.com'
  },
  {
    name: '赵六',
    nickname: '小赵',
    username: 'zhaoliu',
    password: '123456',
    gender: 0, // 0代表女性
    height: 165,
    weight: 55,
    age: 24,
    goal: '减脂',
    dailyCalorieGoal: 1600,
    isActive: true,
    role: 'user',
    email: 'zhaoliu@example.com'
  }
];

/**
 * 检查API状态
 * @returns {Promise} - API状态信息
 */
export async function checkApiStatus() {
  console.group('===== API 状态检查 =====');
  try {
    // 检查API基础URL配置
    const baseURL = axios.defaults.baseURL;
    console.log('API 基础 URL:', baseURL);
    
    // 尝试获取用户列表
    console.log('正在测试用户API...');
    const response = await axios.get('/user', { params: { limit: 1 } });
    
    console.log('API 连接成功! 状态码:', response.status);
    console.log('响应数据类型:', typeof response.data);
    console.log('数据结构:', response.data ? Object.keys(response.data).join(', ') : '空');
    
    return {
      status: 'success',
      message: 'API连接正常',
      data: response.data
    };
  } catch (error) {
    console.error('API 连接失败!', error.message);
    if (error.response) {
      console.error('错误状态:', error.response.status);
      console.error('错误数据:', error.response.data);
    }
    
    return {
      status: 'error',
      message: `API连接失败: ${error.message}`,
      error: error
    };
  } finally {
    console.groupEnd();
  }
}

/**
 * 添加测试用户
 * @param {number} index - 用户模板索引 (0-3)
 * @returns {Promise} - 添加结果
 */
export async function addTestUser(index = 0) {
  console.group('===== 添加测试用户 =====');
  
  try {
    // 确保索引在有效范围内
    const validIndex = Math.min(Math.max(0, index), testUserTemplates.length - 1);
    const userData = { ...testUserTemplates[validIndex] };
    
    // 添加时间戳使用户名唯一
    const timestamp = new Date().getTime().toString().slice(-4);
    userData.username = `${userData.username}${timestamp}`;
    userData.email = `test${timestamp}@example.com`;
    
    console.log('正在添加测试用户:', userData.name);
    console.log('用户数据:', userData);
    
    const response = await addUser(userData);
    console.log('测试用户添加成功!', response.data);
    
    return {
      status: 'success',
      message: `测试用户 ${userData.name} 添加成功!`,
      user: response.data
    };
  } catch (error) {
    console.error('添加测试用户失败:', error.message);
    if (error.response) {
      console.error('错误状态:', error.response.status);
      console.error('错误数据:', error.response.data);
    }
    
    return {
      status: 'error',
      message: `添加测试用户失败: ${error.message}`,
      error: error
    };
  } finally {
    console.groupEnd();
  }
}

/**
 * 批量添加测试用户
 * @param {number} count - 要添加的用户数量 (最多4个)
 * @returns {Promise} - 添加结果
 */
export async function addMultipleTestUsers(count = 4) {
  console.group('===== 批量添加测试用户 =====');
  
  const results = [];
  const validCount = Math.min(Math.max(1, count), testUserTemplates.length);
  
  try {
    console.log(`准备添加 ${validCount} 个测试用户...`);
    
    for (let i = 0; i < validCount; i++) {
      console.log(`添加第 ${i+1}/${validCount} 个测试用户...`);
      const result = await addTestUser(i);
      results.push(result);
      
      // 短暂延迟，避免API限制
      if (i < validCount - 1) {
        await new Promise(resolve => setTimeout(resolve, 500));
      }
    }
    
    const successCount = results.filter(r => r.status === 'success').length;
    console.log(`批量添加完成! 成功: ${successCount}/${validCount}`);
    
    return {
      status: successCount > 0 ? 'success' : 'partial',
      message: `添加了 ${successCount}/${validCount} 个测试用户`,
      results
    };
  } catch (error) {
    console.error('批量添加测试用户失败:', error);
    return {
      status: 'error',
      message: `批量添加测试用户失败: ${error.message}`,
      results,
      error
    };
  } finally {
    console.groupEnd();
  }
}

export default {
  checkApiStatus,
  addTestUser,
  addMultipleTestUsers
}; 